package com.hsogoo.collate.redis;

import com.google.common.collect.Lists;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @Author huangsaigang
 * Created @2019/4/4.
 */
public class RedisSingleConfiguration {

    @Value("${redis.timeout}")
    private Integer timeout;
    @Value("${redis.maxRedirections}")
    private Integer maxRedirections;
    @Value("${redis.cluster.address}")
    private String address;
    @Value("${redis.maxWaitMillis}")
    private int maxWaitMillis;
    @Value("${redis.maxTotal}")
    private int maxTotal;
    @Value("${redis.minIdle}")
    private int minIdle;
    @Value("${redis.maxIdle}")
    private int maxIdle;
    @Value("${redis.auth}")
    private String auth;
    @Value("${redis.testOnReturn:true}")
    private Boolean testOnReturn;
    @Value("${redis.testOnBorrow:true}")
    private Boolean testOnBorrow;

    @Bean
    public JedisPool jedisPool() {
        Set<HostAndPort> haps = this.parseHostAndPort();
        List<HostAndPort> hapList = Lists.newArrayList(haps);
        JedisPoolConfig poolConfig = createJedisPoolConfig();
        String host = hapList.get(0).getHost();
        int port = hapList.get(0).getPort();

        JedisPool jedisPool = null;
        if(StringUtils.isNotBlank(auth) && !"null".equals(auth)){
            jedisPool = new JedisPool(poolConfig, host, port, timeout, auth);
        }else{
            jedisPool = new JedisPool(poolConfig, host, port, timeout);
        }
        return jedisPool;
    }

    @Bean
    public RedisClient redisClient() {
        return new SingleRedisClient();
    }

    private Set<HostAndPort> parseHostAndPort() {
        Set<HostAndPort> haps = new HashSet();
        String[] address = this.address.split(",");

        for(int i = 0; i < address.length; ++i) {
            String[] ipAndPort = address[i].split(":");
            HostAndPort hap = new HostAndPort(ipAndPort[0], Integer.parseInt(ipAndPort[1]));
            haps.add(hap);
        }

        return haps;
    }

    private JedisPoolConfig createJedisPoolConfig() {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxWaitMillis(maxWaitMillis);
        config.setMaxIdle(maxTotal);
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxIdle);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn(testOnReturn);
        return config;
    }

}
